package com.wrench.elevator.tida.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import com.alibaba.fastjson.JSON;
import com.wrench.elevator.tida.constant.Result;
import com.wrench.elevator.tida.exception.WrenchException;

public abstract class WrenchUtil
{
    
    public static final Map<String, Map<String,String>> iosFaceParams = new HashMap<>();
    
    private static final Logger logger = LoggerFactory.getLogger(WrenchUtil.class);
    
    private static String upload_dir = null;
    
    public static List<String> device_aliass;
    
    private static volatile int i = 0;
    
    public static int size;
    
    
    /**
     * 获取文件
     * */
    public static MultipartFile getFile(HttpServletRequest request, String fileName)
    {
        String contentType = request.getContentType();
        if (contentType != null && contentType.toLowerCase().startsWith("multipart/"))
        {
            MultipartHttpServletRequest multipartRequest =
                WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
            MultipartFile file = multipartRequest.getFile(fileName);
            
            return file;
        }
        return null;
    }


    public static void main(String[] args) {
        System.out.println(isInt("0.2"));
    }
    
   
    
    public static String saveFacePic(MultipartFile user_face_pic, String user_id, HttpServletRequest request)
    {
        if (WrenchUtil.hasNull(upload_dir))
        {
            upload_dir = request.getSession().getServletContext().getRealPath("upload") + "/";
        }
        new File(upload_dir + user_id).mkdirs();
        String fileName = user_face_pic.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = System.currentTimeMillis() + suffix;
        try
        {
            user_face_pic.transferTo(new File(upload_dir + user_id + "/" + newFileName));
        }
        catch (IllegalStateException | IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "upload/" + user_id + "/" + newFileName;
    }
    
    public static boolean isVaildGender(String gender)
    {
        return stringEquals(Dict.FACE_GENDER_F, gender) || stringEquals(Dict.FACE_GENDER_M, gender)
            || stringEquals(Dict.FACE_GENDER_X, gender);
    }
    
    public static void forward(HttpServletRequest request, HttpServletResponse response, String url)
    {
        try
        {
            request.getRequestDispatcher(url).forward(request, response);
        }
        catch (ServletException | IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * 判断是否是金额数字 整数或者2位内小数
     * */
    public static boolean isMoneyStr(String str)
    {
        return isInt(str) || isDouble(str);
    }
    
    /**
     * 判断手机格式是否正确 正确 true
     */
    public static boolean isVaildPhone(String phone)
    {
        return phone.matches(Dict.PHONE_REGEX);
    }
    
    /**
     * 响应字符串
     */
    public static void responseStr(HttpServletResponse response, String str)
    {
        PrintWriter out = getWriter(response);
        if (!hasNull(out))
        {
            out.print(str);
        }
    }
    
    /**
     * 是否有null对象 有 true
     */
    public static boolean hasNull(Object... objects)
    {
        for (Object object : objects)
        {
            
            if (object == null)
                return true;
            
        }
        return false;
    }
    
    /**
     * 判断两个字符串相等 相等 true
     * */
    public static boolean stringEquals(String a, String b)
    {
        if (hasNull(a, b))
            return false;
        return a.equals(b);
    }
    
    /**
     * 判断字符串是否为 “” 是true
     * */
    public static boolean stringIsBlank(String... strings)
    {
        for (String string : strings)
        {
            if ("".equals(string.trim()))
                return true;
        }
        return false;
    }
    
    /**
     * getWriter()
     */
    private static PrintWriter getWriter(HttpServletResponse response)
    {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = null;
        try
        {
            out = response.getWriter();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            logger.error("==> WrenchUtil.getWriter() -- response.getWriter() Error , error =>{}", e);
        }
        return out;
    }
    
    /**
     * 响应map
     */
    public static void responseMap(HttpServletResponse response, Map<String, Object> map)
    {
        String responseStr = null;
        try
        {
            responseStr = JSON.toJSONString(map);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            logger.error("==> WrenchUtil.responseMap() -- JSON.toJSONString Error , error =>{}", e);
        }
        if (!hasNull(responseStr))
            responseStr(response, responseStr);
        
    }
    
    /**
     * 调用存储过程需要的map k1 v1 k2 v2 k3 v3 ,,,
     * 
     * @throws WrenchException
     * */
    public static ModelMap getParamMap(ModelMap map, Object... objects)
        throws WrenchException
    {
        int len = objects.length;
        if (len % 2 != 0)
        {
            throw new WrenchException(Result.WRONG_PARAM_NUM_CODE, Result.WRONG_PARAM_NUM_MESSAGE);
        }
        
        for (int i = 0; i < len; i += 2)
        {
            map.put(objects[i].toString(), objects[i + 1]);
        }
        System.out.println("map........................................" + map.get("face_count"));
        return map;
    }
    
    /**
     * 取参数
     */
    public static String getPara(HttpServletRequest request, String paraName)
    {
        try
        {
            request.setCharacterEncoding("utf-8");
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            logger.error("==> WrenchUtil.getPara() -- request.setCharacterEncoding Error , error =>{}", e);
        }
        String paraValue = null;
        try
        {
            paraValue = request.getParameter(paraName);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            logger.error("==> WrenchUtil.getPara() -- request.getParameter Error , error =>{}", e);
        }
        return paraValue;
    }
    
    /**
     * 取参数组
     */
    public static String[] getParas(HttpServletRequest request, String paraName)
    {
        try
        {
            request.setCharacterEncoding("utf-8");
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            logger.error("==> WrenchUtil.getParas() -- request.setCharacterEncoding Error , error =>{}", e);
        }
        String[] paraValue = null;
        try
        {
            paraValue = request.getParameterValues(paraName);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            logger.error("==> WrenchUtil.getParas() -- request.getParameter Error , error =>{}", e);
        }
        return paraValue;
    }
    
    /**
     * 判断是否是一个整数
     */
    public static boolean isInt(String str)
    {
        return str.matches(Dict.INT_REGEX);
    }
    
    /**
     * 批量判断是否都是整数
     */
    public static boolean areInt(String... strs)
    {
        for (String str : strs)
        {
            if (!isInt(str))
                return false;
        }
        return true;
    }
    
    /**
     * 判断是否是一个小数
     */
    public static boolean isDouble(String str)
    {
        return str.matches(Dict.DOUBLE_REGEX);
    }
    
    /**
     * 批量判断是否都是小数
     */
    public static boolean areDouble(String... strs)
    {
        for (String str : strs)
        {
            if (!isInt(str))
                return false;
        }
        return true;
    }
    
    /**
     * 极光推送给电梯板子
     * */
    public static void pushToJiaoxiang(String device_alias, Map<String, Object> contents)
    {
        boolean isPushed = JPushUtil.pushToJiaoxiang(contents, device_alias);
        if (isPushed)
            logger.debug("==> isPushed true ------>  , contents = {}  ", JSON.toJSON(contents));
    }
}
